#region Using

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using BEGalleryExtension;

#endregion

[Extension("Creates a Photo Gallery using the BEGalleryExtension assembly.", "1.3", "<a href=\"http://www.jwendl.net\">Justin Wendlandt</a>")]
public class PhotoGallery
{
    public PhotoGallery()
	{
		Post.Serving += new EventHandler<ServingEventArgs>(Serving);
		Page.Serving += new EventHandler<ServingEventArgs>(Serving);
        Comment.Serving += new EventHandler<ServingEventArgs>(Serving);

        ExtensionManager.SetAdminPage("PhotoGallery", "~/secure/ImportHandler.axd"); 
	}

    private static int pageSize = 9;
    private static int repeatColumns = 3;
    private static readonly Regex regex = new Regex(@"\[photo:(.*?)\]|\[album:(.*?)\]|\[gallery\]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
    private static void Serving(object sender, ServingEventArgs e)
	{
        if (!e.Body.Contains("[photo:") && !e.Body.Contains("[album:") && !e.Body.Contains("[gallery"))
            return;

        Match match = regex.Match(e.Body);
        string expr = match.Groups[0].Value;
        int id = 0;
        Int32.TryParse(match.Groups[1].Value.Trim(), out id);

        QueryString query = new QueryString();
        int AlbumID = -1;
        int PageNum = 0;
        string albumID = query["AlbumID"];
        string pageNum = query["pg"];
        Int32.TryParse(albumID, out AlbumID);
        Int32.TryParse(pageNum, out PageNum);

        if (expr.Contains("photo"))
        {
            string photoID = match.Groups[1].Value;
            Image img = new Image();
            img.ImageUrl = String.Format(Constants.PhotoHandler, photoID, "large");

            string photoHtml = "";
            using (StringWriter sw = new StringWriter())
            {
                img.RenderControl(new System.Web.UI.HtmlTextWriter(sw));
                photoHtml = sw.ToString();
            }

            e.Body = e.Body.Replace(expr, photoHtml);
        }

        if (expr.Contains("album"))
        {
            AlbumControl album = new AlbumControl();
            PhotoListControl photos = new PhotoListControl();

            Int32.TryParse(match.Groups[1].Value, out AlbumID);
            album.DirectoryID = AlbumID;
            album.RepeatColumns = 4;
            photos.CurrentPage = PageNum;
            photos.DirectoryID = AlbumID;
            photos.PageSize = pageSize;
            photos.RepeatColumns = repeatColumns;

            string html = "";
            html += generateHtml(album);
            html += "<br /><hr /><br />";
            html += generateHtml(photos);

            e.Body = e.Body.Replace("[gallery]", html);
        }

        if (expr.Contains("gallery"))
        {
            if (!string.IsNullOrEmpty(query["PhotoID"]))
            {
                FullPhotoControl photo = new FullPhotoControl();
                photo.PhotoID = Convert.ToInt32(query["PhotoID"]);
                photo.DirectoryID = Convert.ToInt32(query["AlbumID"]);

                HyperLink prev = photo.getPreviousLink(query);
                HyperLink next = photo.getNextLink(query);
                HyperLink link = photo.getAlbumLink(query);

                string html = "";
                html += generateHtml(prev);
                html += generateHtml(link);
                html += generateHtml(next);
                html += "<br />";
                html += generateHtml(photo);

                e.Body = e.Body.Replace("[gallery]", html);
            }
            else
            {
                AlbumControl album = new AlbumControl();
                PhotoListControl photos = new PhotoListControl();

                album.DirectoryID = AlbumID;
                album.RepeatColumns = 4;
                photos.CurrentPage = PageNum;
                photos.DirectoryID = AlbumID;
                photos.PageSize = pageSize;
                photos.RepeatColumns = repeatColumns;

                string html = "";
                html += generateHtml(album);
                html += "<br /><hr /><br />";
                html += generateHtml(photos);

                e.Body = e.Body.Replace("[gallery]", html);
            }
        }
	}

    private static string generateHtml(WebControl ctl)
    {
        string output = "";
        using (StringWriter sw = new StringWriter())
        {
            ctl.RenderControl(new System.Web.UI.HtmlTextWriter(sw));
            output = sw.ToString();
        }
        return output;
    }
}
